const db = require('../db/index')

// bcrypt 加密
const bcrypt = require('bcryptjs')
// jsonwebtoken 生成 token
const jwt = require('jsonwebtoken')
// 导入文件处理模块
const fs = require('fs')
// crypto 库生成唯一标识符 onlyId
const crypto = require('crypto')


// --------------------------------个人信息--------------------------------------------


// 上传头像 前端参数: { image_url: file } 后端返回: { status: 0, onlyId, url }
exports.uploadAvatar = (req, res) => {
  // 生成唯一标识
  const onlyId = crypto.randomUUID()
  // 服务器生成请求的图片名称: 995a488ee71fc975086fec8a40f012ce
  let oldName = req.files[0].filename
  // 服务器生成请求的图片文件名: 2.JPG
  let req_originalname = req.files[0].originalname
  // Buffer.from() 方法用于将以 Latin-1 编码的字符串转换为 UTF-8 编码
  let newName = Buffer.from(req_originalname, 'latin1').toString('utf8')
  // fs.renameSync() 方法用于重命名文件或目录
  fs.renameSync('./public/upload/' + oldName, './public/upload/' + newName)
  const sql = `insert into image set ?`
  db.query(sql, {
    image_url: `http://localhost:3007/upload/${newName}`,
    onlyId
  }, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      onlyId,
      url: 'http://localhost:3007/upload/' + newName
    })
  })
}

// 绑定账号 前端参数: { onlyId, url, account } 后端返回: { status: 0, message: '绑定成功' }  
exports.bindAccount = (req, res) => {
  const {
    account,
    onlyId,
    url
  } = req.body
  const sql = 'update image set account = ? where onlyId = ?'
  db.query(sql, [account, onlyId], (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows == 1) {
      const sql1 = 'update users set image_url = ? where account = ?'
      db.query(sql1, [url, account], (err, result) => {
        if (err) return res.cc(err)
        res.cc('绑定账号成功', 0)
      })
    }
  })
}

// 获取用户信息 前端参数 id 后端返回 {status: 0, message: '获取用户信息成功'}
exports.getUserInfo = (req, res) => {
  const sql = `select * from users where id = ?`
  db.query(sql, req.body.id, (err, result) => {
    if (err) return res.cc(err)
    if (result.length == 0) return res.cc('获取用户信息失败')
    // 密码置空
    result[0].password = ''
    res.send({
      status: 0,
      message: '获取用户信息成功',
      data: result[0]
    })
  })
}

// 修改姓名 前端参数: { id, name } 后端返回: { status: 0, message: '修改姓名成功' }
exports.updateName = (req, res) => {
  const sql = `select * from users where id = ?`
  db.query(sql, req.body.id, (err, result) => {
    if (err) return res.cc(err)
    if (result.length == 0) return res.cc('用户不存在')
    const sql2 = `update users set name = ? where id = ? `
    db.query(sql2, [req.body.name, req.body.id], (err, result) => {
      if (err) return res.cc(err)
      if (result.affectedRows == 1) {
        res.cc('修改姓名成功', 0)
      }
    })
  })
}

// 修改性别 前端参数: { id,sex } 后端返回: { status: 0, message: '修改成功' }
exports.updateSex = (req, res) => {
  const sql = `update users set sex = ? where id = ?`
  db.query(sql, [req.body.sex, req.body.id], (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows == 1) {
      res.cc('修改性别成功', 0)
    }
  })
}

// 修改邮箱前端参数: { id, email } 后端返回: { status: 0, message: '修改成功' }
exports.updateEmail = (req, res) => {
  const sql = `update users set email = ? where id = ?`
  db.query(sql, [req.body.email, req.body.id], (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows == 1) {
      res.cc('修改邮箱成功', 0)
    }
  })
}

// 修改密码 前端参数: { id, oldPwd, newPwd } 后端返回: { status: 0, message: '修改成功' }
exports.updatePassword = (req, res) => {
  const sql = `select * from users where id = ?`
  db.query(sql, req.body.id, (err, result) => {
    if (err) return res.cc(err)
    if (result.length == 0) return res.cc('用户不存在')
    // 判断旧密码是否正确
    const compareResult = bcrypt.compareSync(req.body.oldPassword, result[0].password)
    if (!compareResult) return res.cc('旧密码错误')
    // 加密新密码
    const newPassword = bcrypt.hashSync(req.body.newPassword, 10)
    const sql2 = `update users set password = ? where id = ?`
    // 修改新密码
    db.query(sql2, [newPassword, req.body.id], (err, result) => {
      if (err) return res.cc(err)
      if (result.affectedRows !== 1) return res.cc('修改密码失败')
      res.cc('修改密码成功', 0)
    })
  }
  )
}

// 忘记密码 --- 验证 account 和 email 是否匹配 前端参数: { account, email } 后端返回: { status: 0, message: '匹配成功' }
exports.checkAccountAndEmail = (req, res) => {
  const sql = ` select id, email from users where account = ?`
  db.query(sql, req.body.account, (err, result) => {
    if (err) return res.cc(err)
    if (result.length == 0) return res.cc('用户不存在')
    if (result[0].email !== req.body.email) return res.cc('账号邮箱不匹配')
    res.send({
      status: 0,
      message: '匹配成功',
      id: result[0].id
    })
  })
}

// 忘记密码 --- 修改密码 前端参数: {id, newPassword } 后端返回: { status: 0, message: '修改成功' }
exports.updatePasswordByAccount = (req, res) => {
  const newPassword = bcrypt.hashSync(req.body.newPassword, 10)
  const sql = `update users set password = ? where id = ?`
  db.query(sql, [newPassword, req.body.id], (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows !== 1) return res.cc('修改密码失败')
    res.cc('修改密码成功', 0)
  })
}


// --------------------------------用户管理--------------------------------------------


// 创建管理员 --- 参数: account, password, name, email, sex , department, identity
exports.creatAdmin = (req, res) => {
  // 判断用户是否存在 ---不存在才可以创建管理员
  const { account, password, name, email, sex, department, identity } = req.body
  const sql = `select * from users where account = ?`
  db.query(sql, account, (err, result) => {
    if (err) return res.cc(err)
    if (result.length !== 0) return res.cc('账号已存在')
    // 若不存在 --- 加密密码添加用户
    const password = bcrypt.hashSync(req.body.password, 10)
    const create_time = new Date()
    const sql2 = `insert into users set ?`
    db.query(sql2, { account, password, name, email, sex, department, identity, create_time }, (err, result) => {
      if (err) return res.cc(err)
      if (result.affectedRows !== 1) return res.cc('创建失败')
      res.cc('创建管理员成功', 0)
    })
  })
}

// 获取管理员列表 --- 参数: identity
exports.getAdminList = (req, res) => {
  const sql = `select * from users where identity = ?`
  db.query(sql, req.body.identity, (err, result) => {
    if (err) return res.cc(err)
    // 把密码置空
    result.forEach(item => {
      item.password = ''
    })
    res.send({
      status: 0,
      message: '获取管理员列表成功',
      data: result
    })
  })
}

// 编辑管理员信息 参数: id,  name, email, sex , department
exports.updateAdminInfo = (req, res) => {
  const { id, name, email, sex, department } = req.body
  const date = new Date()
  const sql = `select department from users where id = ?`
  db.query(sql, id, (err, result) =>{
    if (err) return res.cc(err)
    // 修改的不是部门
    if (result[0].department == department) {
			const updateContent = {
				id,
				name,
				sex,
				email,
				department,
				update_time: date,
			}
      const sql2 = 'update users set ? where id = ?'
			db.query(sql2, [updateContent, updateContent.id], (err, result) => {
				if (err) return res.cc(err)
				res.send({
					status: 0,
					message: '修改管理员信息成功'
				})
			})
    } else {
      // 修改了部门 更新 read_list 和 read_status
      const updateContent = {
        id,
        name,
        sex,
        email,
        department,
        update_time: date,
        read_list: null,
        read_status: 0
      }
      const sql3 = 'update users set ? where id = ?'
      db.query(sql3, [updateContent, updateContent.id], (err, result) => {
				if (err) return res.cc(err)
				res.send({
					status: 0,
					message: '修改管理员信息成功'
				})
			})
		}
  })
}

// 对管理员降职为用户 参数: id
exports.updateAdminToUser = (req, res) => {
  const sql = `update users set identity = '用户' where id = ?`
  db.query(sql, req.body.id, (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows !== 1) return res.cc('修改失败')
    res.cc('降职为用户成功', 0)
  })
}

// 用户升为管理员 参数: identity, id
exports.updateUserToAdmin = (req, res) => {
  const sql = `update users set identity = ? where id = ?`
  db.query(sql, [req.body.identity, req.body.id], (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows !== 1) return res.cc('更新身份失败')
    res.cc('升为管理员', 0)
  })
}

// 通过账号搜索用户 参数: account identity
exports.searchUserByAccount = (req, res) => {
  const sql = `select * from users where account = ? and identity = ?`
  db.query(sql, [req.body.account, req.body.identity], (err, result) => {
    if (err) return res.cc(err)
    if (result.length == 0) return res.cc('用户不存在')
    // 把密码置空
    result.forEach(item => {
      item.password = ''
    })
    res.send({
      status: 0,
      message: '搜索成功',
      data: result
    })
  })
}

// 冻结用户 把 status 置为 1  参数: id
exports.freezeUser = (req, res) => {
  const sql = `update users set status = ? where id = ?`
  db.query(sql, [req.body.status, req.body.id], (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows !== 1) return res.cc('冻结失败')
    res.cc('冻结成功', 0)
  })
}

// 解冻用户 把 status 置为 0 参数: id
exports.unfreezeUser = (req, res) => {
  const sql = `update users set status = ? where id = ?`
  db.query(sql, [req.body.status, req.body.id], (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows !== 1) return res.cc('解冻失败')
    res.cc('解冻成功', 0)
  })
}

// 获取冻结用户列表  参数: 无
exports.getFreezeUserList = (req, res) => {
  const sql = `select * from users where status = 1 and identity = '用户'`
  db.query(sql, (err, result) => {
    if (err) return res.cc(err)
    // 把密码置空
    result.forEach(item => {
      item.password = ''
    })
    res.send({
      status: 0,
      message: '获取冻结用户列表成功',
      data: result
    })
  })
}

// 删除用户 参数: id account
exports.deleteUser = (req, res) => {
  const sql = `delete from users where id = ?`
  db.query(sql, req.body.id, (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows !== 1) return res.cc('删除失败, 此 id 不存在')
    // 继续删除 iamge 表中对应用户的图片
    const sql2 = `delete from image where account = ?`
    db.query(sql2, req.body.account, (err, result) => {
      if (err) return res.cc(err)
      res.cc('删除成功', 0)
    })

  })
}


// 通过部门获取用户列表 参数: department
exports.getUserListByDepartment = (req, res) => {
  const sql = `select * from users where department = ? and identity = '用户'`
  db.query(sql, [req.body.department], (err, result) => {
    if (err) return res.cc(err)
    if (result.length == 0) return res.cc('用户不存在')
    // 把密码置空
    result.forEach(item => {
      item.password = ''
    })
    res.send({
      status: 0,
      message: '搜索成功',
      data: result
    })
  })
}

// 获取对应身份的用户总数 参数: identity
exports.getUserCountByIdentity = (req, res) => {
  const sql = `select count(*) as total from users where identity = ?`
  db.query(sql, req.body.identity, (err, result) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '获取用户总数成功',
      data: result[0].total
    })
  })
}

// 换页时: 根据条目个数截取用户列表  参数: identity, pager
exports.getUserListByPager = (req, res) => {
  const pager = (req.body.pager - 1) * 5
  // limit 为截取多少条数据 offset 为 从第几行截取
  const sql = `select * from users where identity = ? limit 5 offset ${pager}`
  db.query(sql, req.body.identity, (err, result) => {
    if (err) return res.cc(err)
    // 把密码置空
    result.forEach(item => {
      item.password = ''
    })
    res.send({
      status: 0,
      message: `获取第${req.body.pager}页用户列表成功`,
      data: result
    })
  })
}

// 获取部门数据
exports.getDepartmentList = (req, res) => {
  const sql = `select distinct department from users `
  db.query(sql, (err, result) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '获取部门列表成功',
      data: result
    })
  })
}